package com.dhcc.core.modules.gen.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.beetl.core.GroupTemplate;
import org.beetl.core.resource.ClasspathResourceLoader;

import com.dhcc.core.framework.exception.BizException;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.DateUtil;
import com.dhcc.core.modules.gen.entity.Column;
import com.dhcc.core.modules.gen.entity.Table;

/**
 * 代码生成器 工具类
 * 
 * @ClassName: GenUtils
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午9:35:00
 */
public class GenUtils {

    public static List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        templates.add("Entity.java.btl");
        templates.add("Dao.java.btl");
        templates.add("Dao.xml.btl");
        templates.add("Service.java.btl");
        templates.add("ServiceImpl.java.btl");
        templates.add("Controller.java.btl");
        templates.add("page.html.btl");
        templates.add("page.js.btl");
        templates.add("page_info.js.btl");
        templates.add("page_edit.html.btl");
        templates.add("page_add.html.btl");
        return templates;
    }

    /**
     * 
     * 生成代码
     * 
     * @Title: generatorCode
     * @Description: TODO
     * @param modularName
     *            模块名
     * @param customName
     *            自定义包名
     * @param author
     *            作者
     * @param tablePrefix
     *            表前缀
     * @param usePermission
     *            使用权限控制
     * @param useLog
     *            使用日志
     * @param table
     *            表名
     * @param columns
     *            列名
     * @param zip
     *            输出zip
     * @return: void
     */
    public static void generatorCode(String modularName, String customName, String author, String tablePrefix,
            int usePermission, int useLog, Table table, List<Column> columns,
            ZipOutputStream zip) {
        // 配置信息
        Configuration config = getConfig();
        // 包名
        String packageName = config.getString("package") + "." + modularName;
        packageName += CommonUtil.isNotEmpty(customName) ? "." + customName : "";
        // 作者
        author = CommonUtil.isEmpty(author) ? config.getString("author") : author;
        // 表信息
        // 表名转换成Java类名
        String className = tableToJava(table.getTableName(), tablePrefix);
        table.setClassName(className);
        table.setClassname(StringUtils.uncapitalize(className));

        // 列信息
        List<Column> columsList = new ArrayList<>();
        for (Column column : columns) {

            // 列名转换成Java属性名
            String attrName = columnToJava(column.getColumnName());
            column.setAttrName(attrName);
            column.setAttrname(StringUtils.uncapitalize(attrName));

            // 列的数据类型，转换成Java类型
            String tmpKey = table.getDatabaseId()+"."+column.getDataType();
            tmpKey = StringUtils.lowerCase(tmpKey);
            String attrType = config.getString(tmpKey, "unknowType");
            column.setAttrType(attrType);

            // 是否主键
            if (CommonUtil.equals(column.getColumnName(),"id")||CommonUtil.equals(column.getColumnName(),"ID")) {
                table.setPk(column);
            }

            columsList.add(column);
        }
        table.setColumns(columsList);

        // 没主键，则第一个字段为主键
        if (table.getPk() == null) {
            table.setPk(table.getColumns().get(0));
        }

        // 设置beetl资源加载器
        ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("codeTemplate/");
        org.beetl.core.Configuration cfg;
        try {
            cfg = org.beetl.core.Configuration.defaultConfiguration();
            cfg.setStatementStart("##");
            cfg.setStatementEnd(null);
            GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
            
            // 封装模板数据
            Map<String, Object> map = new HashMap<>();
            map.put("use_permission", usePermission);
            map.put("use_log", useLog);
            map.put("modularName", modularName);
            map.put("customName", customName);
            map.put("tableName", table.getTableName());
            map.put("comments", table.getComments());
            map.put("pk", table.getPk());
            map.put("className", table.getClassName());
            map.put("classname", table.getClassname());
            map.put("pathName", table.getClassname().toLowerCase());
            map.put("columns", table.getColumns());
            map.put("package", packageName);
            map.put("author", author);
            map.put("datetime", DateUtil.now());

            // 获取模板列表
            List<String> templates = getTemplates();
            for (String template : templates) {
                // 渲染模板
                org.beetl.core.Template t = gt.getTemplate(template);
                t.binding(map);
                String str = t.render();
                try {
                    // 添加到zip
                    zip.putNextEntry(new ZipEntry(getFileName(template, table.getClassName(), packageName,
                            modularName, table.getClassname().toLowerCase())));
                    IOUtils.write(str, zip, "UTF-8");
                    zip.closeEntry();
                } catch (IOException e) {
                    throw new BizException("渲染模板失败，表名：" + table.getTableName(), e);
                }
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replace(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new BizException("获取配置文件失败，", e);
        }
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, String className, String packageName, String modularName,
            String pathName) {
        String packagePath = "src/main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }

        if (template.contains("Entity.java.btl")) {
            return packagePath + "entity" + File.separator + className + "Entity.java";
        }

        if (template.contains("Dao.java.btl")) {
            return packagePath + "dao" + File.separator + className + "Mapper.java";
        }

        if (template.contains("Dao.xml.btl")) {
            return packagePath + "dao" + File.separator + "mapping" + File.separator + className + "Mapper.xml";
        }

        if (template.contains("Service.java.btl")) {
            return packagePath + "service" + File.separator + "I" + className + "Service.java";
        }

        if (template.contains("ServiceImpl.java.btl")) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains("Controller.java.btl")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }

        if (template.contains("page.html.btl")) {
            return "sys-home" + File.separator + "view" + File.separator + "backend" + File.separator + modularName
                    + File.separator + pathName + File.separator + pathName + ".html";
        }
        if (template.contains("page_edit.html.btl")) {
            return "sys-home" + File.separator + "view" + File.separator + "backend" + File.separator + modularName
                    + File.separator + pathName + File.separator + pathName + "_edit.html";
        }
        if (template.contains("page_add.html.btl")) {
            return "sys-home" + File.separator + "view" + File.separator + "backend" + File.separator + modularName
                    + File.separator + pathName + File.separator + pathName + "_add.html";
        }
        if (template.contains("page.js.btl")) {
            return "sys-home" + File.separator + "static" + File.separator + "backend" + File.separator + modularName
                    + File.separator + pathName + File.separator + pathName + ".js";
        }
        if (template.contains("page_info.js.btl")) {
            return "sys-home" + File.separator + "static" + File.separator + "backend" + File.separator + modularName
                    + File.separator + pathName + File.separator + pathName + "_info.js";
        }
        return null;
    }
}
